import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Link } from 'react-router';
import {  Icon,Tabs,message,Row, Col,Input,DatePicker,Button,Table,Form,Select,Cascader,Upload,Spin,Modal } from 'antd';
import NavBar from '../common/NavBar';
import ContentBody from '../common/ContentBody';
import api from '../api';
import moment from 'moment';
import axios from 'axios';

import $ from 'jquery';

const TabPane = Tabs.TabPane;
const FormItem = Form.Item;
const Option = Select.Option;
import {
} from '../constants/index';

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 20 },
  },
};

const formItemLayout1 = {
  labelCol:{
    xs:{span:24},
    sm:{span:8},
  },
  wrapperCol:{
    xs:{span:24},
    sm:{span:12}
  }

}

const formItemLayout2 = {
  labelCol:{
    xs:{span:24},
    sm:{span:0},
  },
  wrapperCol:{
    xs:{span:24},
    sm:{span:24}
  }

}


class FinanceCompanyEdit extends React.Component {
    constructor(props, context){
        super(props, context);
        var {loan_id,operate_type} = props.location.query||{};
        this.state={
          loan_id,
          operate_type,
          addition:{
            pledge_type:'0'
          },
          loading:false,
          provinces:[],
          cities:[],
          regions:[],
          previewVisible:false,
          fileList:[],
          company:{
            license:[],
          },
        };
        
    }
    componentWillMount(){
      let{id} = this.props.location.query || {};
      this.doFetchProvinces();
      if (id) {
        this.getDetailById(id);
      }
      // this.doFetch();
      // this.doFetchLoanDetail()
    }
    // componentDidMount() {
    //   var {addition} =this.state;
    //     const { setFieldsValue } = this.props.form;
    //     setFieldsValue(addition)
    // }

    componentWillReceiveProps(nextProps){
      // this.doFetchLoanDetail()
    }

    async getDetailById(id){
      let {fileList=[],previewImage} = this.state;
      let result = await api('/system/financeCompany/detail',{id});

      if (result.success) {

        this.doFetchCities(result.data.province_code);
        this.doFetchRegions(result.data.city_code);
        if (result.data && result.data.license && result.data.license.length != 0 ) {
          fileList.push({
            name:result.data.license[0].name,
            url:result.data.license[0].previewUrl,
            uid:result.data.license[0].client_uid,
            status:'done'
          })
          previewImage = result.data.license[0].previewUrl;
        }
        
        this.setState({
          company:result.data,
          loading:false,
          fileList,
          previewImage,
        })
      }else{
        this.setState({
          loading:false,
        })
      }
    }


    //获取省份
    async doFetchProvinces(){
      this.setState({loading:true});
      var result = await api('/common/getProvinces',{});
      if (result.success) {
        this.setState({
          provinces:result.data,
          loading:false,
        })
      }else{
        this.setState({
          loading:false,
        })
        message.error(result.message);
      }
    }
    //获取城市
    async doFetchCities(provinceCode){
      this.setState({loading:true});
      let result = await api('/common/getCities',{code:provinceCode});
      if (result.success) {
        this.setState({
          cities:result.data,
          loading:false,
        })
      }else{
        this.setState({
          loading:false,
        })
        message.error(result.message);
      }
    }

    //获取地区
    async doFetchRegions(cityCode){
      this.setState({loading:true});
      let result = await api('/common/getRegions',{code:cityCode});
      if (result.success) {
        this.setState({
          regions:result.data,
          loading:false,
        })
      }else{
        this.setState({
          loading:false,
        })
        message.error(result.message);
      }
    }


    //选择省份
    onProvinceChange(value){
      let{company} = this.state;
      company.province_code = value;
      company.city_code = "";
      company.area_code = "";
      this.setState({
        company,
      })
      this.doFetchCities(value);
    }

    //选择城市
    onCityChange(value){
      let {company} = this.state;
      company.area_code = "";
      this.setState({
        company,
      })
      this.doFetchRegions(value);
    }

    //选择地区
    onRegionChange(value){
      let {company} = this.state;
      company.area_code = value;
      this.setState({
        company,
      })
    }

    
    uuid(){
      return Math.random().toString(32).slice(2)
    }

    

    save(addNext){
      const {validateFieldsAndScroll,setFields } = this.props.form;
      validateFieldsAndScroll((errors,values) =>{
        if (errors) {
          return;
        }
        this.setState({
          loading:true,
        })
        let {company,loading} = this.state;
        company  = {...company,...values};

        let {id} = this.props.location.query||{};
        if (id) {
          company.id = id;
          this.update(company);
        }else{
          this.submit(company,addNext);
        }
        
      })

    }
    reqs = {};
    //保存
    async submit(company,addNext){
      let result = await api('/system/financeCompany/add',{company});
      if (result.success) {
        message.success("创建成功",2,() => {
          if (addNext == "addNext") {

            this.setState({
              loading:false,
              cities:[],
              regions:[],
              previewVisible:false,
              fileList:[],
              company:{
                license:[],
              },

            })
            const {resetFields} = this.props.form;
            resetFields();
            this.context.router.push(`/systemManage/financeCompany/edit`)
          }else{
            this.setState({
              loading:false,
            })
            this.context.router.push(`/systemManage/financeCompany/list`)
          }
          
        })
      }else{
        message.error(result.message);
        this.setState({
          loading:false,
        })
      }
        
    }

    //更新
    async update(company){
      let result = await api('/system/financeCompany/update',{company});
      if (result.success) {
        message.success("更新成功");
        this.setState({
          loading:false,
        })
        this.context.router.push(`/systemManage/financeCompany/list`)
      }else{
        message.error(result.message);
        this.setState({
          loading:false,
        })
      }
    }

    
  handleCancel = () => this.setState({ previewVisible: false })

  handlePreview = (file) => {
      this.setState({
          previewImage: file.url || file.thumbUrl,
          previewVisible: true
      });
  }

  handleChange = ({ fileList }) => {

    let {company} = this.state;
    company.license = [];
    if (fileList.length == 0) {//删除
      this.setState({
        fileList:[],
        company,
      })
    }else{
      this.setState({
        fileList,
      })
    }
    // var {company} = this.state;
    // if (fileList && fileList.length > 0) {
    //   company.logo = fileList[0].response;
    // }else{
    //   company.logo = '';
    // }
    
    // this.setState({ fileList,company })
  }

  componentWillUnmount(){

  }

uploadFiles = (params) =>{
  this.uploadFile(params);  
}


  //上传
  async uploadFile(params){

    let {
      file,
      filename,
    } = params;

    this.setState({
      loading:true
    })
    let {fileList=[],company} = this.state;
    let result = await api.upload('/file/upload?file_type=1',file);
    if(result.success){
      fileList.push({
        name:filename,
        url:result.data.previewUrl,
        uid:file.uid,
        status:'done'
      })
      company.license.push({
        name:result.data.name,
        type:result.data.type,
        url:result.data.url,
        client_uid:file.uid,
      })
      this.setState({
        fileList,
        previewImage:result.data.previewUrl,
        company,
      })
    }
    this.setState({
      loading:false,
    })
  }





    render() {
      const { getFieldDecorator, getFieldsError, getFieldError, isFieldTouched ,setFieldsValue} = this.props.form;
        var {provinces,cities,regions,previewVisible,previewImage,fileList,company} = this.state;
        let {id} = this.props.location.query;
       return (
          <Spin spinning={this.state.loading}>
          <div className="containerWithBorder margin20 bgWhite">
            <div className="margin15">{id?"编辑客户信息":"添加客户"}</div>
            <div className="padding15 containerWithTopAndBottomBorder" style={{backgroundColor:"#EFEFEF"}}>
              {id?null:
                  <Button
                    type="primary"
                    className="marginR15"
                    onClick={this.save.bind(this,"addNext")}
                  >保存并继续添加</Button>
              }
              
              <Button
                type="primary"
                className="marginR15"
                onClick={this.save.bind(this,"addOnlyOne")}
              >保存</Button>
              <Button
                type="primary"
                className="marginR15"
                onClick={() =>{

                  this.context.router.push(`/systemManage/financeCompany/list`);
                }}
              >取消</Button>
            </div>
            <h2 className="type-title margin15">基本信息</h2>
            <div className="containerWithBottomBorder marginL15 marginR15"></div>
            <Form className="type-body marginT10 marginL15">
              <Row>
                <Col span={12}>
                    <FormItem 
                      {...formItemLayout}
                      label="公司名称"
                    >
                      {getFieldDecorator('name', {
                        rules: [
                          {
                            required: true,
                            message: '请输入公司名称',
                          },
                        ],
                        initialValue:company&&company.name?company.name:"",
                      })(
                        <Input 
                          placeholder="公司名称" 

                        />
                      )}
                      
                    </FormItem>
                </Col>

              </Row>
              <Row>
                <Col span={12}>
                  <FormItem 
                    {...formItemLayout}
                    label="公司简称"
                  >
                    {getFieldDecorator('short_name', {
                      rules: [
                        {
                          required: true,
                          message: '请输入公司简称',
                        },
                      ],
                        initialValue:company&&company.short_name?company.short_name:"",
                    })(
                      <Input 
                        placeholder="公司简称" 
                      />
                    )}
                      
                  </FormItem>
                </Col>
              </Row>

              <Row>
                <Col span={6}>
                  <FormItem 
                    {...formItemLayout1}
                    label="注册城市"
                  >
                    {getFieldDecorator('province', {
                      rules: [
                        {
                          required: true,
                          message: '请选择注册省',
                        },
                      ],
                        initialValue:company&&company.province_code?company.province_code.toString():"",
                    })(
                      <Select onChange={this.onProvinceChange.bind(this)} placeholder="请选择省" >
                        <Option value="">请选择</Option>
                        {
                          provinces.map((item,index) => {
                            return (
                              <Option key={item.code} value={item.code.toString()}>{item.name}</Option>
                              )
                          })
                        }
                      </Select>
                    )}
                      
                  </FormItem>
                </Col>
                <Col span={3}
                style={{marginLeft:"-20px",marginRight:"20px"}}
                >
                  <FormItem 
                    {...formItemLayout2}
                    s
                  >
                    {getFieldDecorator('city', {
                      rules: [
                        {
                          required: true,
                          message: '请选择注册城市',
                        },
                      ],
                        initialValue:company&&company.city_code?company.city_code.toString():"",
                    })(
                      <Select onChange={this.onCityChange.bind(this)} placeholder="请选择市" >
                        <Option key="0" value="">请选择</Option>
                        {
                          cities.map((item,index) => {
                            return (
                                <Option key={item.code} value={item.code.toString()}>{item.name}</Option>
                              )
                          })
                        }
                      </Select>
                    )}
                      
                  </FormItem>
                </Col>
                <Col span={3}>
                  <FormItem 
                    {...formItemLayout2}
                  >
                    {getFieldDecorator('region', {
                      rules: [
                        {
                          required: true,
                          message: '请选择注册地区',
                        },
                      ],
                        initialValue:company&&company.area_code?company.area_code.toString():"",
                    })(
                      <Select onChange={this.onRegionChange.bind(this)} placeholder="请选择地区" >
                        <Option key="0" value="">请选择</Option>
                        {
                          regions.map((item,index) => {
                            return (
                                <Option key={item.code} value={item.code.toString()}>{item.name}</Option>
                              )
                          })
                        }
                      </Select>
                    )}
                      
                  </FormItem>
                </Col>

              </Row>

              <Row>
                <Col span={12}>
                  <FormItem 
                    {...formItemLayout}
                    label="详细地址"
                  >
                    {getFieldDecorator('address', {
                      rules: [
                        {
                          required: true,
                          message: '请输入详细地址',
                        },
                      ],
                        initialValue:company&&company.address?company.address:"",
                    })(
                      <Input 
                        placeholder="详细地址" 
                      />
                    )}
                      
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <FormItem 
                    {...formItemLayout}
                    label="所属行业"
                  >
                    {getFieldDecorator('industry', {
                      rules: [
                        {
                          required: true,
                          message: '请输入所属行业',
                        },
                      ],
                        initialValue:company&&company.industry?company.industry:"",
                    })(
                      <Input 
                        placeholder="所属行业" 
                      />
                    )}
                      
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <FormItem 
                    {...formItemLayout}
                    label="企业性质"
                  >
                    {getFieldDecorator('nature', {
                      rules: [
                        {
                          required: true,
                          message: '请输入企业性质',
                        },
                      ],
                      initialValue:company && company.nature?company.nature.toString():"0",
                    })(
                      <Select 
                        placeholder="企业性质" 
                      > 
                        <Select.Option key="0" value="0">请选择</Select.Option>
                        <Select.Option key="1" value="STATE_OWNED">国企</Select.Option>
                        <Select.Option key="2" value="PRIVATE">民企</Select.Option>
                        <Select.Option key="3" value="STATE_OWNED_LISTING">国企（上市）</Select.Option>
                        <Select.Option key="4" value="PRIVATE_LISTING">民企（上市）</Select.Option>
                      </Select>
                    )}
                      
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <FormItem 
                    {...formItemLayout}
                    label="法人代表"
                  >
                    {getFieldDecorator('representative', {
                      rules: [
                        {
                          required: true,
                          message: '请输入法人代表',
                        },
                      ],
                      initialValue:company && company.representative?company.representative:"",
                    })(
                      <Input 
                        placeholder="法人代表" 
                      />
                    )}
                      
                  </FormItem>
                </Col>
              </Row>

              <Row>
                <Col span={12}>
                  <FormItem 
                    {...formItemLayout}
                    label="营业执照"
                  >
                    {getFieldDecorator('licenseImg', {
                      rules: [
                        {
                          required: false,
                          message: '请上传营业执照',
                        },
                      ],
                    })(
                      <div className="clearfix">
                          <Upload
                              name="license"
                              listType="picture-card"
                              fileList={fileList}
                              onPreview={this.handlePreview}
                              onChange={this.handleChange}
                              accept={'image/*'}
                              customRequest={this.uploadFiles}
                          >
                              {fileList.length >= 1 ? null : (<div>
                                  <Icon type="plus" />
                                  <div className="ant-upload-text">添加图片</div>
                              </div>)}
                          </Upload>
                          <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel.bind(this,'image')}>
                              <img alt="example" style={{ width: '100%' }} src={previewImage} />
                          </Modal>
                      </div>
                    )}
                      
                  </FormItem>
                </Col>
              </Row>
            </Form>

          </div>


          </Spin>
          
            
        )
    }
}

FinanceCompanyEdit.contextTypes= { router: React.PropTypes.object.isRequired};

export default  Form.create()(FinanceCompanyEdit);
